<?php 
class kdtrace_tnt extends Controller {
	
	function track( $tracknum , $lang = ""){
		if($lang=="ch"){$langset = "zh";} else {$langset = "en";};
		$getdata = "respCountry=cn&respLang=".$langset."&navigation=1&page=1&sourceID=1&sourceCountry=ww&plazaKey=&refs=&requesttype=GEN&searchType=CON&cons=" . $tracknum;
		$url 	 = "http://www.tnt.com/webtracker/tracking.do" ;
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $getdata);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
			'Content-Type: application/x-www-form-urlencoded',
			'Referer: http://www.tnt.com/express/en_cn/site/home.html',
			'User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36' 
		));

		$result = curl_exec($ch);
        curl_close($ch);
		$rtndata = array('tracknum'=>$tracknum,'header'=>array(),'err'=>array(),'eventList'=>array());

		if( strpos($result,"Please re-submit your enquiry")>0 || strpos($result,"Sorry we are unable to fulfil your request")>0 || strpos($result , "没有找到您要查询的货件信息")>0){
			$rtndata['err']['errcode'] = '1';
			return $rtndata;
		}
		$rtndata['err']['errcode'] = '0';
		$w1 = strpos($result , '<a xmlns="" name="' . $tracknum . ':1">');
		$w2 = strpos($result , '<hr class="hide" />', $w1);
		$rhtm = iconv("UTF-8" , "GBK//IGNORE" , substr($result , $w1 , $w2 - $w1));
		$rhtm = iconv("GBK" , "UTF-8" ,$rhtm );		//编码互转一次，用于去除影响阅读的乱码。
		$patten = array(
			'zh'=>'/<tr><td>目的地<\/td><td noWrap\="true"><B>(.+?)<\/B><\/td><\/tr>/i',
			'en'=>'/<tr><td>Destination<\/td><td noWrap\="true"><B>(.+?)<\/B><\/td><\/tr>/i'
		);
		if(preg_match($patten[$langset], $rhtm, $matches) == 1){
			$rtndata['header']['shipFrom']      = $matches[1];
		};
		$patten = array(
			'zh'=>'<td>状态</td></tr>',
			'en'=>'<td>Status</td></tr>'
		);

		$w1 = strpos($rhtm , $patten[$langset] );
		$w2 = strpos($rhtm , '</table>' ,$w1);
		$bdhtm = substr($rhtm , $w1 , $w2 - $w1);
		preg_match_all('/<tr vAlign\="top"><td noWrap\="true">(.+?)<\/td><td>(.+?)<\/td><td>(.+?)<\/td><td>(.+?)<\/td><\/tr>/i', $bdhtm, $matches);
		$count = count($matches[0]);
		if($count>0){
			for($i=0 ; $i < $count ; $i++){
				$tt =  strtotime($matches[1][$i] . " " . $matches[2][$i]);
				$rtndata['eventList'][$i] = array(
					"date"			=> date('Y-m-d',$tt),
					"time"			=> date('h:i:s',$tt),
					"utime"			=> $tt,
					"status"		=> $matches[4][$i],
					"location"		=> $matches[3][$i]
				);
			}
		}
		$rtndata['eventList'] = array_reverse( $rtndata['eventList'] );
		return $rtndata;
	}
	
}

?>